<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules;

class RegisterRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        $isEmail = filter_var($this->email, FILTER_VALIDATE_EMAIL);
        
        if ($isEmail) {
            return [
                'name' => 'required|string|max:255',
                'email' => 'required|string|lowercase|email|max:255|unique:users',
                'password' => ['required', 'confirmed', Rules\Password::defaults()],
            ];
        } else {
            return [
                'name' => 'required|string|max:255',
                'email' => 'required|string|regex:/^1[3-9]\d{9}$/|unique:users,phone',
                'password' => ['required', 'confirmed', Rules\Password::defaults()],
            ];
        }
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'email.email' => '请输入有效的邮箱地址',
            'email.regex' => '请输入有效的手机号码',
            'email.unique' => '该邮箱或手机号已被注册',
            'password.confirmed' => '密码确认不匹配',
        ];
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation(): void
    {
        // 如果是手机号，转换为标准格式
        if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
            $this->merge([
                'phone' => $this->email,
            ]);
        }
    }
}